<template>
  <div class="wrap">
    <pro-table
      ref="proTableInst"
      tableTitle="预算列表"
      :columns="columns"
      :request="fetchBudgetPage"
    >
      <template #operation>
        <n-space>
          <n-button type="primary" @click="handleAddBudget">新增预算</n-button>
        </n-space>
      </template>
    </pro-table>

    <pro-dialog
      v-model:showDialog="budgetModalShow"
      :modalProps="modalProps"
      :showButton="true"
      confirmButtonText="确定"
      :showConfirmButton="handleType !== 'check'"
      :cancelButtonText="handleType === 'check' ? '关闭' : '取消'"
      :contentStyle="{ 'padding-left': '10px', 'padding-right': '10px' }"
      width="1000"
      height="500"
      :button-loading="confirmLoading"
      @handleConfirm="budgetConfirm"
      @afterClosed="resetBudgetForm"
      v-bind="$attrs"
    >
      <pro-form
        ref="budgetFormInst"
        v-model:form="budgetForm"
        :formProps="{
          labelPlacement: 'left',
          labelWidth: '100px'
        }"
        :options="budgetFormOptions"
      ></pro-form>
    </pro-dialog>
  </div>
</template>

<script lang="ts" setup name="Budget">
  import { ProTableInst } from '@/components/pro-table/type'
  import { ProFormInst } from '@/components/pro-form/type'
  import { useBudgetApi, useBudgetProForm, useBudgetProTable } from './hooks'
  import { BudgetModel } from '@/api/model/budget-model'
  import { useUser } from '@/store/modules/user'

  const proTableInst = ref<ProTableInst | null>(null)
  const budgetFormInst = ref<ProFormInst | null>(null)

  const budgetModalShow = ref(false)
  const handleType = ref<'add' | 'edit' | 'check'>('check')
  const handleTag = computed(() =>
    handleType.value === 'add'
      ? '新增预算'
      : handleType.value === 'check'
      ? '预算详情'
      : '修改预算'
  )
  const modalProps = computed(() => {
    return {
      showIcon: false,
      title: handleTag.value
    }
  })

  const { userInfo } = storeToRefs(useUser())

  const { budgetForm, resetBudgetForm, budgetFormOptions } = useBudgetProForm({
    handleType
  })

  const handleAddBudget = () => {
    handleType.value = 'add'
    budgetModalShow.value = true
  }

  const handleEditBudget = (row: BudgetModel, type: 'check' | 'edit') => {
    budgetForm.value = row
    handleType.value = type
    budgetModalShow.value = true
  }

  const budgetConfirm = async () => {
    if (await budgetFormInst.value?.handleSubmit()) {
      fetchAddOrEditBudget()
    }
  }

  const {
    fetchBudgetPage,
    fetchAddOrEditBudget,
    fetchDelBudget,
    confirmLoading
  } = useBudgetApi({
    handleType,
    handleTag,
    budgetModalShow,
    budgetForm,
    proTableInst,
    userInfo
  })
  const { columns } = useBudgetProTable({
    handleEditBudget,
    fetchDelBudget
  })
</script>

<style lang="less" scoped></style>
